package org.emet.jee.console.services.department;

import java.util.List;

import org.emet.jee.BusinessException;
import org.emet.jee.console.dao.security.DepartmentDao;
import org.emet.jee.console.entity.security.Department;
import org.emet.jee.console.services.security.SecurityEntityManager;
import org.emet.jee.core.dao.Page;
import org.hibernate.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.security.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RemotingDestination
public class DepartmentManager {
	private static Logger logger = LoggerFactory.getLogger(SecurityEntityManager.class);

	@Autowired
	private DepartmentDao departmentDao;

	@Transactional(readOnly = true)
	@Secured("A_VIEW_DEPARMENT")
	public Department get(Long id) {
		try {
			return departmentDao.get(id);
		} catch (ObjectNotFoundException e) {
			return null;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("error.sys.dept.get", e);
		}

	}

	@Secured("A_MODIFY_DEPARMENT")
	public void save(Department dept) {
		boolean hasSame = departmentDao.hasSameDeptName(dept.getId(), dept.getName());
		if (hasSame)
			throw new BusinessException("error.sys.dept.hasSame");

		try {
			departmentDao.save(dept);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("error.sys.dept.save", e);
		}
	}

	@Secured("A_MODIFY_DEPARMENT")
	public void del(Long... ids) {
		for (Long id : ids) {
			if (notExist(id)) {
				continue;
			}

			try {
				departmentDao.delete(id);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				throw new BusinessException("error.sys.dept.del", e);
			}
		}
	}

	@Transactional(readOnly = true)
	@Secured("A_VIEW_DEPARMENT")
	public Page<Department> search(final Page<Department> page, String deptName) {
		try {
			return departmentDao.search(page, deptName);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("error.sys.dept.search", e);
		}
	}

	@Transactional(readOnly = true)
	@Secured("A_VIEW_DEPARMENT")
	public List<Department> getAll() {
		try {
			return departmentDao.getAll();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("error.sys.dept.getAll", e);
		}
	}

	private boolean notExist(Long id) {
		return get(id) == null;
	}
}
